package indi.jp.project.business.pub.service.impl;

import indi.jp.project.business.pub.dao.MaterialDAO;
import indi.jp.project.business.pub.pojo.po.MaterialPO;
import indi.jp.project.business.pub.pojo.query.MaterialQuery;
import indi.jp.project.core.entity.Datagrid;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.business.pub.service.MaterialService;
import indi.jp.project.core.util.SerialUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

@Service
public class MaterialServiceImpl implements MaterialService {

    @Resource
    private MaterialDAO materialDAO;

    @Resource
    private SerialUtil serialUtil;

    @Override
    public JsonResult queryGrid(MaterialQuery query) throws SQLException {
        List<MaterialPO> list = materialDAO.queryList(query);
        int count = materialDAO.queryCount(query);
        Datagrid<MaterialPO> datagrid = new Datagrid<>(list, count);
        return JsonResult.success(datagrid);
    }

    @Override
    public JsonResult save(MaterialPO materialPO) throws SQLException {
        if (StringUtils.isBlank(materialPO.getId())) {
            String id = String.valueOf(serialUtil.nextId());
            materialPO.setId(id);
            materialDAO.insert(materialPO);
        } else {
            materialDAO.update(materialPO);
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult deleteById(String id) throws SQLException {
        materialDAO.deleteById(id);
        return JsonResult.success();
    }

}
